<?php

/**
 * 库存管理ajax类
 * @package  ajax
 * @subpackage  backend
 * @create by allen.qiang
 */
header('Content-Type:text/html;charset=utf-8');
require 'module/base/wmsHandler.class.php';
class ajax_logistics {

    public function execute() {

        if (isset($_REQUEST['operFlg']) && $_REQUEST['operFlg'] > 0) {

            switch($_REQUEST['operFlg']) {

                case 1: //获取物流公司列表
                    $this->searchList();
                    break;

                case 2: //对物流公司进行更新或保存
                    $this->updateLogistics();
                    break;
                    
                case 3: //物流公司  禁用、启用
                    $this->changeStatus();
                    break;
                    
                case 4: //物流公司配送区域管理列表
                    $this->logisticsRegionList();
                    break;
                    
                case 5: //物流公司配送区域添加或编辑
                    $this->logisticsRegionAdd();
                    break;
                    
                case 6: //城市联动
                    $this->cityChange();
                    break;
                    
                case 7: //删除区域
                    $this->deleteRegion();
                    break;

                case 8: //删除物流公司
                    $this->deleteCompany();
                    break;

                case 9: //上传打印模版背景图
                    $this->uploadTemplateBg();
                    break;

                case 10: //保存模版信息
                    $this->saveTemplate();
                    break;

                case 11:    //物流包裹
                    $this->logisticsPackageCount();
                    break;

                case 12:    //打印设置模版列表
                    $this->printSetTemplate();
                    break;

                case 13:    //打印模版使用状态
                    $this->changeTemplateStatus();
                    break;

                case 14:        //删除打印模版
                    $this->deleteTemplate();
                    break;

                case 15:        //保存配货单打印设置
                    $this->savePrintSetDelivery();
                    break;

                case 16:
                    $this->changeDefault();
                    break;
            }

        }

    }

    /**
     * 获取物流公司列表
     */
    private function searchList() {

        global $G_PGLOB;
        
        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );
        
        //组装查询条件数组
        $search_arr = array(
        	"sortname"=>$_REQUEST['sortname'],
        	"sortorder"=>$_REQUEST['sortorder'],
        	"page"=>$_REQUEST['page'],
        	"rp"=>$_REQUEST['rp']
        );
        
	    try {
	        
	        //查询
	        $result = $commHandler->search( $search_arr , 'wms_logistics' );
	        
	        //组织返回的数据
	        $result_array = array(
	            'page'  => $_REQUEST['page'],
	            'total' => $search_arr['count'],
	            'rows'  => array()
	        );
			
	        if( $result ){
	        	
	        	foreach ( $result as $key=>$value){
	        		
	        		$result_array['rows'][$key] = array(
	                    'id' => $value->logisticsID,
	                    'cell' => array(
	                    	 '<a href="javascript: void(0);" onclick="logistics.edit(' . $value->logisticsID . ');" >修改</a>&nbsp;&nbsp;'.
                            '<a href="javascript: void(0);" onclick="logistics.region(' . $value->logisticsID . ');" >区域</a>&nbsp;&nbsp;',
                            $value->logisticsID,
                            $value->logistics_name,
	                        $value->package_limit,
                            $value->priority
	                    )
	               );
	               
	               if( $value->useFlg == 0 ){
	               	
	               		$result_array['rows'][$key]['cell'][] = '<a href="javascript:void(0);" onclick="logistics.changeConfirm(' . $value->logisticsID . ',' . $value->useFlg . ');">禁用</a>';
	               	
	               }else{
	               	
	               		$result_array['rows'][$key]['cell'][] = '<a href="javascript:void(0);" onclick="logistics.changeConfirm(' . $value->logisticsID . ',' . $value->useFlg . ');">启用</a>';
	               	
	               }
	               
	             
	        		
	        	}
	        	
	        }
	       
	        echo json_encode($result_array);
            return;
        	
        }catch(Exception $e){
        	error_log($e->getMessage());
        	echo json_encode( array('message'=>'系统错误，请与管理员联系','code'=>$e->getCode() ) );
            return;
        }
       
    }
    
    /**
     * 对物流公司进行编辑或保存
     */
    private function updateLogistics() {

        global $G_PGLOB;
        
        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );

       	//接收参数
       	$logisticsID    = $_REQUEST['logisticsID'];
       	$logistics_name = $_REQUEST['logistics_name'];
       	$linkman        = $_REQUEST['linkman'];
       	$mobile         = $_REQUEST['mobile'];
       	$website         = $_REQUEST['website'];
       	$telephone      = $_REQUEST['telephone'];
        $package_limit  = $_REQUEST['package_limit'];
        $priority       = $_REQUEST['priority'];
        $islogistics    = $_REQUEST['islogistics'];
        $hdfk           = $_REQUEST['hdfk'];
       	$useFlg         = $_REQUEST['useFlg'];

       	//检验参数格式
       	if( !empty($mobile) ){
       		if( !$commHandler->isMobile($mobile) ){
                   echo json_encode( array('message'=>'手机格式有误'  , 'code'=>400) );
                   return;
               }

       	}
       	
       	if( !empty($telephone) ){
       		if( !$commHandler->isPhone($telephone) ){
                   echo json_encode( array('message'=>'电话号码格式有误'  , 'code'=>400) );
                   return;
               }

       	}
        
       	$logistics_obj = new entity('wms_logistics');
       	
       	if( !empty($logisticsID) ){

            $logistics_obj->logisticsID = $logisticsID;
       		
       		if( !$G_PGLOB->DBCA->fetch($logistics_obj) ){
                   echo json_encode( array('message'=>'没有找到当前信息' , 'code'=>404 ) );
                   return;
               }
       		
       	}else{
       		
       		$logistics_obj->creator = $G_PGLOB->currentUserID;
       		
       	}

        //查询出物流公司名称为“$logistics_name”的信息
        $checkLogistics_sql = 'SELECT * from wms_logistics WHERE logistics_name=?';
        $checkLogistics_result = $G_PGLOB->DBCA->stmt_query($checkLogistics_sql,'s',$logistics_name);

        //检查该物流公司名称是否已经存在
        if( $checkLogistics_result ){
            if($logisticsID && $checkLogistics_result[0]->logisticsID != $logisticsID ){
                echo json_encode( array('message'=>'物流公司名称重复' , 'code'=>400 ) );
                return;
            }elseif( empty($logisticsID) ){
                echo json_encode( array('message'=>'物流公司名称重复' , 'code'=>400 ) );
                return;
            }
        }

        //检查优先级是否已经存在
        $check  = array('priority'=>$priority);
        $result = $commHandler->search($check,'wms_logistics');

        if( $result ){
            if($logisticsID && $result[0]->logisticsID != $logisticsID ){
                echo json_encode( array('message'=>'该优先级已存在，请重新填写' , 'code'=>400 ) );
                return;
            }elseif( empty($logisticsID) ){
                echo json_encode( array('message'=>'该优先级已存在，请重新填写' , 'code'=>400 ) );
                return;
            }
        }

       $logistics_obj->package_limit  = $package_limit;
       $logistics_obj->priority       = $priority;
       $logistics_obj->islogistics    = $islogistics;
       $logistics_obj->logistics_name = $logistics_name;
       $logistics_obj->linkman        = $linkman;
       $logistics_obj->mobile         = encryptD($mobile);
       $logistics_obj->telephone      = encryptD($telephone);
       $logistics_obj->website      = $website;
       $logistics_obj->hdfk           = $hdfk;
       $logistics_obj->useFlg         = $useFlg;
       $logistics_obj->templateID     = $_REQUEST['templateID'];
       
       try{
       	
       		$G_PGLOB->DBCA->save( $logistics_obj );
       		
       		if( $logisticsID ){
       			echo json_encode( array('message'=>'更新成功' , 'code'=>200 ) );
                return;
       		}else{
       			echo json_encode( array('message'=>'保存成功' , 'code'=>200 ) );
                return;
       		}
       		
       	
       }catch(Exception $e){
       	
	       	error_log( $e->getMessage() );
	       	echo json_encode( array('message'=>'系统错误，请与管理员联系' , 'code'=>500 ) );
            return;
       }
       
      
       	
		
    }
    
     /**
     * 物流公司 禁用、启用
     */
    private function changeStatus() {

        global $G_PGLOB;

        $logisticsID = $_REQUEST['logisticsID'];
        $flg   = $_REQUEST['flg'];
		
        $logistics_obj = new entity('wms_logistics');
       	$logistics_obj->logisticsID = $logisticsID;
       	
       	if( !$G_PGLOB->DBCA->fetch($logistics_obj) ){
       		
       		echo json_encode( array('message'=>'没有找到当前信息' , 'code'=>404 ) );
            return;
       		
       	}else{
       		
       		$userFlg = $logistics_obj->useFlg;

            if( $flg == 1 && $userFlg == 0){
                echo json_encode( array('message'=>'编号['.$logisticsID.']物流公司已处于<b>禁用</b>状态<br>请重新刷新页面' , 'code'=>400 ) );
                return;
            }

            if( $flg == 0 && $userFlg == 1){
                echo json_encode( array('message'=>'编号['.$logisticsID.']物流公司已处于<b>启用</b>状态<br>请重新刷新页面' , 'code'=>400 ) );
                return;
            }
       		
       		if( $userFlg == 0 ){
       			$logistics_obj->useFlg = 1;
       		}else{
       			$logistics_obj->useFlg = 0;
       		}
       		
       	}
       	
       try{
       	
       		$G_PGLOB->DBCA->save( $logistics_obj );
       		
       		if( $userFlg == 0 ){
       			echo json_encode( array('message'=>'已启用' , 'code'=>200 ) );
                return;
       		}else{
       			echo json_encode( array('message'=>'已禁用' , 'code'=>200 ) );
                return;
       		}
       		
       	
       }catch(Exception $e){
       	
	       	error_log( $e->getMessage() );
	       	echo json_encode( array('message'=>'系统错误，请与管理员联系' , 'code'=>500 ) );
            return;
       }

    }
    
    
    /**
     * 查询公司配送区域信息
     */
    private function logisticsRegionList() {

        global $G_PGLOB;
        
        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );
        
        if( empty( $_REQUEST['logisticsID'] ) ){
            echo json_encode( array('message'=>'参数错误' , 'code'=>400) );
            return;
        }

        
        //组装查询条件数组
        $search_arr = array(
        	"sortname"=>$_REQUEST['sortname'],
        	"sortorder"=>$_REQUEST['sortorder'],
        	"page"=>$_REQUEST['page'],
        	"rp"=>$_REQUEST['rp'],
        	"logisticsID"=>$_REQUEST['logisticsID']
        );

	    try {
	        
	        //查询
	        $result = $commHandler->search( $search_arr , 'wms_logistics_detail' );

	        //组织返回的数据
	        $result_array = array(
	            'page'  => $_REQUEST['page'],
	            'total' => $search_arr['count'],
	            'rows'  => array()
	        );

	        if( $result ){
	        	
	        	foreach ( $result as $key=>$value){

                        //连接配送区域字符串
                        $regionString = '';

                        //查询配送区域
                        $searchregion = array(
                            'logisticsID'=>$value->logisticsID,
                            'logistics_region_id'=> $value->logistics_region_id,
                           );
                        $logisticsRegion = $commHandler->search( $searchregion , 'wms_logistics_region' );

                        if( $logisticsRegion ){

                            foreach ( $logisticsRegion as $k=>$val ){

                                //查询配送区域的名称
                                $regionSearch = array('id'=>$val->regionID);
                                $regionList = $commHandler->search($regionSearch,'sys_region');

                                //超过八个记录就换行
                                if(  $k != 0 && ($k+1) % 9 == 0 ){

                                    //连接字符串
                                    $regionString .= ',<br>' . $regionList[0]->name;

                                }else{

                                    //连接字符串
                                    $regionString .= ',' . $regionList[0]->name;

                                }

                            }

                        }

                        if( $regionString != '' ){
                            $regionString = substr($regionString,1);
                        }

                        $result_array['rows'][$key] = array(
                            'id' => $value->logistics_region_id,
                            'cell' => array(
                                 '<a href="javascript: void(0);" onclick="region.edit(' . $value->logisticsID . ',' . $value->logistics_region_id .');" >修改</a>',
                                 $value->logistics_region_id
                            )
                       );

                       if( $value->regionType == 1 ){

                            $result_array['rows'][$key]['cell'][] = '货到付款';

                       }else{

                            $result_array['rows'][$key]['cell'][] = '款到发货';

                       }

                        $result_array['rows'][$key]['cell'][] = $value->logistics_region_name;
                        $result_array['rows'][$key]['cell'][] = $regionString;
//                        if( $value->standardFlg == 1 ){
//                            $result_array['rows'][$key]['cell'][] = number_format($value->freight,2,'.','').'元/公斤';
//                            $result_array['rows'][$key]['cell'][] = number_format($value->overStandard,2,'.','').'元/公斤';
//                        }else{
//                            $result_array['rows'][$key]['cell'][] = number_format($value->freight,2,'.','').'元/立方米';
//                            $result_array['rows'][$key]['cell'][] = number_format($value->overStandard,2,'.','').'元/立方米';
//                        }



	        	}

	        	
	        }

	        echo json_encode($result_array);
        	return;
        }catch(Exception $e){
        	error_log($e->getMessage());
        	echo json_encode( array('message'=>'系统错误，请与管理员联系','code'=>$e->getCode() ) );
        	return;
        }
       
    }
    
    /**
     * 添加或编辑物流公司配送区域
     */
   private function logisticsRegionAdd(){
   	
   		global $G_PGLOB;
   		
   		//实例化公共类
   		$commHandler = new commHandler($G_PGLOB->DBCA);
   		
   		//获取参数
   		$logisticsID         = $_REQUEST['logisticsID'];
   		$logistics_region_id = $_REQUEST['logistics_region_id'];
        $regionType          = $_REQUEST['regionType'];
//        $standardFlg         = $_REQUEST['standardFlg'];
//        $standard            = $_REQUEST['standard'];
//        $overStandard        = $_REQUEST['overStandard'];
   		
   		$region_detail_obj = new entity('wms_logistics_detail');
   		$region_detail_obj->logisticsID = $logisticsID;
        $region_detail_obj->regionType = $regionType;
   		
   		if( !empty( $logistics_region_id ) ){

            $region_detail_obj->logistics_region_id = $logistics_region_id;
   			
   			if( !$G_PGLOB->DBCA->fetch( $region_detail_obj ) ){
   				
   				echo json_encode( array( 'message'=>'没有找到相关信息' , 'code'=>404 ) );
   				return;
   				
   			}
   			
   		}else{
   			
   			//获取生码
   			$logistics_region_id = $commHandler->generate_seqno('seqno_logisticsregion');
   			if( empty( $logistics_region_id ) || $logistics_region_id == 0 ){
   				//将sequence插入初始值0
            	$G_PGLOB->DBCA->stmt_query('INSERT INTO seqno_logisticsregion value(0)');
   				$logistics_region_id =  $commHandler->generate_seqno('seqno_logisticsregion');
   			}
   			$region_detail_obj->logistics_region_id = $logistics_region_id;
   			$region_detail_obj->creator             = $G_PGLOB->currentUserID;
   			
   		}
   		
   		$region_detail_obj->logistics_region_name = $_REQUEST['logistics_region_name'];
//   		$region_detail_obj->freight               = $_REQUEST['freight'];
//        $region_detail_obj->standardFlg           = $standardFlg;
//        $region_detail_obj->standard              = $standard;
//        $region_detail_obj->overStandard          = $overStandard;

       //先将该物流公司原区域信息删除
       $deleteSQL = 'DELETE FROM wms_logistics_region WHERE logisticsID=? AND logistics_region_id=?';
   		
   		try {
   			
			//开启事务
			$G_PGLOB->DBCA->beginTransaction();
			
			//保存详细信息
   			$G_PGLOB->DBCA->save($region_detail_obj);

            //删除该物流公司下的次区域ID中的区域信息
            $G_PGLOB->DBCA->stmt_query($deleteSQL,'ii',array($logisticsID,$logistics_region_id));

   			//保存区域信息
	   		foreach ( $_REQUEST['params'] as $value ){

	   			$region_region_obj = new entity('wms_logistics_region');
		   		$region_region_obj->logisticsID = $logisticsID;
		   		$region_region_obj->logistics_region_id = $logistics_region_id;
		   		$region_region_obj->regionID = $value['id'];
                $region_region_obj->regionType = $regionType;

		   		//查询该区域ID的等级
	   			$level_sql = 'SELECT region_level FROM sys_region WHERE id=?';
	   			$level     = $G_PGLOB->DBCA->stmt_query($level_sql,'i',$value['id']);
	   			
	   			$region_region_obj->creator = $G_PGLOB->currentUserID;
	   			$region_region_obj->levelFlg = $level[0]->region_level;
	   			
	   			$G_PGLOB->DBCA->save( $region_region_obj );
	   			
	   		}
			
			//提交事务
            $G_PGLOB->DBCA->commit();
            
            echo json_encode( array( 'message'=>'保存成功' , 'code'=>200 ) );
   			return;
   			
   		}catch (Exception $e){
   			
   			//回滚事务
            $G_PGLOB->DBCA->rollBack();
            error_log( $e->getMessage() );
   			echo json_encode( array( 'message'=>'系统错误，请与管理员联系' , 'code'=>500 ) );
   			return;
   		}

   }
    
    /**
     * 城市联动
     */
    function cityChange(){
    	
    	global $G_PGLOB;
    	
    	/**
    	 * 获取参数
    	 * $flg   1:选取城市   2：选取区
    	 */
    	$id = $_REQUEST['id'];
    	$flg = $_REQUEST['flg'];
    	
    	//查询语句
    	$sql_search = 'SELECT id,name,parentID,region_level FROM sys_region WHERE parentID=? AND region_level=?';
    	
    	if( $flg == 1 ){
    		
    		$result = $G_PGLOB->DBCA->stmt_query($sql_search , 'ii' , array($id , 2) );
    		
    	}else{
    		
    		$result = $G_PGLOB->DBCA->stmt_query($sql_search , 'ii' , array($id , 3) );
    		
    	}
    	
    	$params = array();
    	
    	if( $result ){
    		
    		foreach ( $result as $value ){
    			$params[] = array( 'id'=>$value->id , 'name'=>$value->name );
    		}
    		
    	}
    	
    	echo json_encode( array( 'code'=>200 , 'data'=>$params) );
    	return;
    }
    
    /**
     *  删除配送区域
     */
   private function deleteRegion(){
   	
   		global $G_PGLOB;

       //实例化公共类
       $commHandler = new commHandler( $G_PGLOB->DBCA );
   		
   		/**获取参数
        * $_REQUEST[delArr] => Array(
                                       [0] => 19
                                       [1] => 18
                                       [2] => 17
                                     )
            *这是由要删除的配送区域ID组成的数组
        */
       $logisticsID = $_REQUEST['logisticsID'];
   	   $delArr      = $_REQUEST['delArr'];
   		
   		if( empty($logisticsID) ){
   			echo json_encode( array('message'=>'参数错误' , 'code'=>400) );
   			return;
   		}

       //查询物流公司是否存在
       $searchCompany = array('logisticsID'=>$logisticsID);
       $result        = $commHandler->search($searchCompany,'wms_logistics');

       if( empty($result) ){
           echo json_encode( array('message'=>'没有找到与该区域相对应的物流公司信息' , 'code'=>400) );
           return;
       }

       //删除配送区域详情表里的数据
       $detail_delete_sql = 'DELETE FROM wms_logistics_detail WHERE logisticsID=? AND logistics_region_id=?';

       //删除配送区域表里的数据
       $region_delete_sql = 'DELETE FROM wms_logistics_region WHERE logisticsID=? AND logistics_region_id=?';

       //记录不存在的记录
       $errorNum = 0;
       $errorArr = array();
//       $regionType = 0;

       //循环删除配送区域
       if( $delArr ){

           foreach ( $delArr as $val ){

               //检查配送区域详情表里是否存在相应的数据
               $region_detail_obj = new entity('wms_logistics_detail');
               $region_detail_obj->logisticsID = $logisticsID;
               $region_detail_obj->logistics_region_id = $val;

               //检查配送区域表里是否存在相应的数据
               $region_obj = new entity('wms_logistics_region');
               $region_obj->logisticsID = $logisticsID;
               $region_obj->logistics_region_id = $val;

               if( !$G_PGLOB->DBCA->fetch($region_detail_obj) || !$G_PGLOB->DBCA->fetch($region_obj) ){
                   $errorNum++;
                   $errorArr[] = $val;
               }

//               if( $region_detail_obj->regionType == 1 )
//                   $regionType = 1;

           }

//           if( $regionType == 1 ){
//               echo json_encode( array('message'=>'货到付款配送区域不可删除，请重新操作' , 'code'=>400 ) );
//               return;
//           }

           if( $errorNum > 0 ){

               echo json_encode( array('message'=>'所选部分区域已不存在，请刷新页面' , 'code'=>400 ) );
               return;

           }else{

               try{

                   //开启事务
                   $G_PGLOB->DBCA->beginTransaction();

                   //循环删除配送区域详情和其对应的配送区域
                   foreach( $delArr as $value ){

                       //删除详情表里的数据
                       $G_PGLOB->DBCA->stmt_query($detail_delete_sql , 'ii' , array($logisticsID,$value) );

                       //删除区域设置信息
                       $G_PGLOB->DBCA->stmt_query($region_delete_sql , 'ii' , array($logisticsID,$value) );

                   }

                   //提交事务
                   $G_PGLOB->DBCA->commit();

                   echo json_encode( array('message'=>'删除成功', 'code'=>200) );
                   return;


               }catch (Exception $e){

                   $G_PGLOB->DBCA->rollBack();
                   error_log($e->getMessage());
                   echo json_encode( array('message'=>'系统错误，请与管理员联系', 'code'=>500) );
                   return;

               }

           }


       }else{

           echo json_encode( array('message'=>'请选择要删除的配送区域' , 'code'=>400 ) );
           return;

       }
   		
   }

    //删除物流公司
    function deleteCompany(){

        global $G_PGLOB;

        //实例化公共类
        $commHandler = new commHandler( $G_PGLOB->DBCA );

        /**接收参数
         *
         * $_REQUEST[delArr] => Array(
                                        [0] => 19
                                        [1] => 18
                                        [2] => 17
                                      )
         *这是由要删除的物流公司ID组成的数组
         */
        $delArr = $_REQUEST['delArr'];

        //删除物流公司
        $del_logistics = 'DELETE FROM wms_logistics WHERE logisticsID=?';

        //删除物流公司下的配送区域详情
        $del_logistics_detail = 'DELETE FROM wms_logistics_detail WHERE logisticsID=?';

        //删除物流公司下的配送区域
        $del_logistics_region = 'DELETE FROM wms_logistics_region WHERE logisticsID=?';

        //统计不存在的公司的数目
        $errorNum_logistics = 0;
        $errorArr = array();

        if( $delArr ){

            //检查要删除的物流公司是否全部存在
            foreach( $delArr as $value ){

                //检查物流公司是否存在
                $checkArr = array('logisticsID'=>$value);
                $result   = $commHandler->search($checkArr,'wms_logistics');

                if( !$result ){
                    $errorArr[] = $value;
                    $errorNum_logistics++;
                }

            }

            if( $errorNum_logistics > 0 ){

                echo json_encode( array('message'=>'所选部分公司已不存在，请刷新页面' , 'code'=>400 ) );
                return;

            }else{

                try{

                    //开启事务
                    $G_PGLOB->DBCA->beginTransaction();

                    //循环删除物流公司和其对应的配送区域
                    foreach( $delArr as $value ){

                        //删除物流公司
                        $G_PGLOB->DBCA->stmt_query($del_logistics,'i',$value);

                        //删除物流公司
                        $G_PGLOB->DBCA->stmt_query($del_logistics_detail,'i',$value);

                        //删除物流公司
                        $G_PGLOB->DBCA->stmt_query($del_logistics_region,'i',$value);

                    }

                    //提交事务
                    $G_PGLOB->DBCA->commit();

                    echo json_encode( array('message'=>'删除成功', 'code'=>200) );
                    return;

                }catch( Exception $e ){

                    $G_PGLOB->DBCA->rollBack();
                    error_log($e->getMessage());
                    echo json_encode( array('message'=>'系统错误，请与管理员联系', 'code'=>500) );
                    return;

                }

            }

        }else{

            echo json_encode( array('message'=>'请选择要删除的公司' , 'code'=>400 ) );
            return;

        }

    }

    /**
     * 上传打印模版背景图
     */
    private function uploadTemplateBg(){

        //上传路径
        $upload_path = 'quanliadmin/docroot/home/print/logistics/';

        //图片格式
        $img_array = array('jpg','jpeg','png','bmp');

        //分解文件名和扩展名
        list($filename,$extension) = explode('.',$_FILES['upload_bg']['name']);

        //检查图片格式是否正确
        if(!in_array($extension,$img_array)){
            echo "<script>window.parent.template.err_msg('请上传格式正确的图片');</script>";
            return;
        }

        //检查文件夹
        if(!file_exists(G_APPLICATION_BASEPATH.$upload_path)){
            mkdir(G_APPLICATION_BASEPATH.$upload_path,0777,true);
        }

        //windows下用GBK
        $file_name = iconv('utf-8','gbk',$_FILES['upload_bg']['name']);
        if(!move_uploaded_file($_FILES['upload_bg']['tmp_name'],G_APPLICATION_BASEPATH.$upload_path.$file_name)){
            echo "<script>window.parent.template.err_msg('系统错误，上传失败');</script>";
            return;
        }

        //更新页面文件路径
        echo "<script>window.parent.bg_path = '/".$upload_path.$_FILES['upload_bg']['name']."';</script>";

        return;
    }

    /**
     * 保存打印模版信息
     */
    private function saveTemplate(){
        global $G_PGLOB;

        if(!isset($_REQUEST['code']) || empty($_REQUEST['code']) ){
            echo json_encode(array('code' => 400 , 'message' => '缺少参数保存失败'));
            return;
        }

        //仓库类
        $wmsHandler = new wmsHandler($G_PGLOB->DBCA,$G_PGLOB->currentUserID);

        //保存数据
        $data_array = array();

        //打印代码组装为数组
        $code_array = explode(';',$_POST['code']);

        //背景图片路径
        $data_array['path'] = trim($_POST['path']);

        //类型
        $data_array['type'] = trim($_POST['type']);

        //模版名称
        $data_array['template_name'] = trim($_POST['template_name']);

        //模版ID
        $data_array['templateID'] = trim($_POST['templateID']);

        foreach ($code_array as $value){
            //纸张大小参数
            if(strpos($value,'PRINT_INITA')){
                $data_array['code']['init'] = substr($value,strpos($value,'(')+1,-1);
            }
            //标签数据参数
            if(strpos($value,'ADD_PRINT_TEXTA')){
                $temp = explode(',',substr($value,strpos($value,'(')+1,-1));
                $data_array['code']['params'][trim($temp[0],'"')] = $temp;
            }
        }

        //执行保存方法
        $reuslt_array = $wmsHandler->saveTemplatePrintSet($data_array);

        echo json_encode($reuslt_array);

        return;
    }

    /**
     * 统计物流公司发货包裹及重量
     */
    private function logisticsPackageCount(){
        global $G_PGLOB;

        //设置了起始日期则使用起始日期，否则默认当天
        if(isset($_REQUEST['startDate']) && !empty($_REQUEST['startDate']) ){
            $_REQUEST['startDate'] = trim($_REQUEST['startDate'])." 00:00:00";
        }else{
            $_REQUEST['startDate'] = date('Y-m-d')." 00:00:00";
        }

        //日期，否则默认当天
        if(isset($_REQUEST['endDate']) && !empty($_REQUEST['endDate']) ){
            $_REQUEST['endDate'] = trim($_REQUEST['endDate'])." 23:59:59";
        }else{
            $_REQUEST['endDate'] = date('Y-m-d')." 23:59:59";
        }

        $sql = "SELECT COUNT(*) cnt,SUM(goods_weight) total_weight,logistics_name,logisticsID FROM wms_package WHERE dispatch_time BETWEEN ? AND ? GROUP BY logisticsID";

        try{

            $result_data = $G_PGLOB->DBCA->stmt_query($sql,'ss',$_REQUEST['startDate'],$_REQUEST['endDate']);

            //\返回数组
            $result_array = array(
                'page'  => $_REQUEST['page'],
                'rows'  => array()
            );

            if($result_data){
                $result_array['total'] =  count($result_data);

                foreach ($result_data as $key => $value){
                    $result_array['rows'][$key] = array(
                        "id" => "logisticsID",
                        "cell" => array(
                            $value->logistics_name,
                            $value->cnt,
                            $value->total_weight
                        ),
                    );
                }
            }

            echo json_encode($result_array);
        }catch (Exception $e){
            error_log($e->getMessage());
            echo json_encode(array('code' => 500 , 'message' => '系统错误,信息查询失败'));
        }

        return;
    }

    /**
     * 打印设置模版
     */
    private function printSetTemplate(){
        global $G_PGLOB;

        if(!isset($_REQUEST['type']) || !is_numeric(trim($_REQUEST['type'])) ){
            die( json_encode( array('code' => 400 , 'message' => '参数错误') ) );
        }

        //查询条件
        $sql_str = '';

        //查询条件类型
        $sql_type = 'i';

        //查询值
        $sql_value[] = trim($_REQUEST['type']);

        //按编号查
        if(isset($_REQUEST['templateID']) && is_numeric(trim($_REQUEST['templateID'])) ){
            $sql_str .= " AND templateID = ? ";
            $sql_type .= 'i';
            $sql_value[] = trim($_REQUEST['templateID']);
        }

        //按模版名称
        if(isset($_REQUEST['template_name']) && !empty($_REQUEST['template_name']) ){
            $sql_str .= " AND template_name LIKE ? ";
            $sql_type .= 's';
            $sql_value[] = "%".trim($_REQUEST['template_name'])."%";
        }

        //排序
        $sql_order = '';
        if(isset($_REQUEST['sortname'])){
            $_REQUEST['sortname'] = trim($_REQUEST['sortname']);
            $_REQUEST['sortorder'] = $_REQUEST['sortorder'] ? $_REQUEST['sortorder'] : '';
            if(!empty($_REQUEST['sortname'])){
                $sql_order .= " ORDER BY ".$_REQUEST['sortname']." ".$_REQUEST['sortorder'];
            }
        }

        //limit
        $sql_limit = '';
        if(isset($_REQUEST['rp']) && is_numeric($_REQUEST['rp']) && $_REQUEST['rp'] > 0 ){
            $_REQUEST['page'] = isset($_REQUEST['page']) && is_numeric($_REQUEST['page']) && $_REQUEST['page'] > 0 ? $_REQUEST['page'] : 1;
            $sql_limit .= " LIMIT ".($_REQUEST['page']-1)*$_REQUEST['rp'].",".$_REQUEST['rp'];
        }

        //模版条数
        $sql_count = "SELECT COUNT(*) cnt FROM wms_print_template WHERE type = ?".$sql_str.$sql_limit;
        $result_count = $G_PGLOB->DBCA->stmt_query($sql_count,$sql_type,$sql_value);

        //查询模版信息
        $sql = "SELECT templateID,template_name,useFlg,type,isDefault FROM wms_print_template WHERE type = ? ".$sql_str.$sql_order.$sql_limit;
        $result = $G_PGLOB->DBCA->stmt_query($sql,$sql_type,$sql_value);

        //组织返回的数据
        $result_array = array(
            'page'  => $_REQUEST['page'],
            'total' => $result_count[0]->cnt,
            'rows'  => array()
        );

        if( $result ){

            foreach ( $result as $key=>$value){
                //使用标志
                $useFlg = '';
                if($value->useFlg == 1){
                    $useFlg = "<span id='useFlg_".$value->templateID."'><a href='javascript:void(0);' onclick='print.changStatus(".$value->templateID.",1);'  >启用</a></span>";
                }else{
                    $useFlg = "<span id='useFlg_".$value->templateID."'><a href='javascript:void(0);' onclick='print.changStatus(".$value->templateID.",0);' >禁用</a>";
                }
                //是否默认
                $isDefault = '';
                if($value->isDefault == 1){
                    $isDefault = "是";
                }else{
                    $isDefault = "<span id='default_".$value->templateID."'><a href='javascript:void(0);' onclick='print.changDefault(".$value->templateID.");' >否</a>";
                }

                $result_array['rows'][$key] = array(
                    'id' => $value->templateID,
                    'cell' => array(
                        '<a href="javascript: void(0);" onclick="print.edit(' . $value->templateID . ','.$value->type.');" >修改</a>&nbsp;&nbsp;',
                        $useFlg,
                        $isDefault,
                        $value->templateID,
                        $value->template_name,
                    )
                );

                if($_REQUEST['type'] == 2){     //打印模版不显示：是否默认
                    array_splice($result_array['rows'][$key]['cell'],2,1);
                }

            }

        }


        echo json_encode($result_array);

        return;
    }

    /**
     * 改变打印模版使用状态
     */
    private function changeTemplateStatus(){
        global $G_PGLOB;

        if(!isset($_REQUEST['templateID']) || !is_numeric($_REQUEST['templateID']) ){
            die( json_encode( array('code' => 400 ,'message' => '缺少模版ID') ) );
        }

        try{

            $wms_print_template = new entity('wms_print_template');
            $wms_print_template->templateID = $_REQUEST['templateID'];
            if(!$G_PGLOB->DBCA->fetch($wms_print_template)){
                throw new Exception('未获取模版信息',404);
            }
            $wms_print_template->useFlg = $wms_print_template->useFlg ? 0 : 1;

            $G_PGLOB->DBCA->save($wms_print_template);

            echo json_encode(array('code' => 200 ,'message' => 'ok' , 'templateID' => $_REQUEST['templateID'] , 'useFlg' => $wms_print_template->useFlg));

        }catch (Exception $e){
            if($e->getCode() == 404){
                echo json_encode(array('code' => $e->getCode() ,'message' => $e->getMessage()));
            }else{
                error_log($e->getMessage());
                echo json_encode(array('code' => 500 ,'message' => '系统错误'));
            }
        }

        return;
    }

    /**
     * 删除模版
     * $_POST['templateID'] = array( 'id1' ,'id2' , ...  );
     */
    private function deleteTemplate(){
        global $G_PGLOB;

        if(!isset($_REQUEST['templateID']) || !is_array($_REQUEST['templateID']) || empty($_REQUEST['templateID']) ){
            die( json_encode( array('code' => 400, 'message' => '请选择删除的模版') ) );
        }

        $sql = "DELETE FROM wms_print_template WHERE templateID = ?";

       try{

           foreach ($_REQUEST['templateID'] as $templateID){
               $G_PGLOB->DBCA->stmt_query($sql,'i',$templateID);
           }

           echo json_encode(array('code' => 200 , 'message' => 'ok'));

       }catch (Exception $e){
           error_log($e->getMessage());
            echo json_encode(array('code' => 500 , 'message' => '系统错误，删除失败'));
       }

        return;
    }

    /**
     * 保存配货单打印设置
     */
    private function savePrintSetDelivery(){
        global $G_PGLOB;

        if(!isset($_POST['template_name']) || empty($_POST['template_name']) ){
            die( json_encode( array( 'code' => 400 , 'message' => '请输入模版名称' ) ) );
        }

        $wmsHandler = new wmsHandler($G_PGLOB->DBCA,$G_PGLOB->currentUserID);

        //重新组织选择的字段
        $_POST['field'] = array_flip($_POST['field']);
        foreach ($_POST['field'] as $key => &$value){
            $value = $key;
        }

        $result = $wmsHandler->savePrintSetDelivery($_POST);

        echo json_encode($result);

        return;
    }

    /**
     * 改变默认
     * $_POST['templateID'] = int 模版ID
     */
    private function changeDefault(){
        global $G_PGLOB;

        if(!isset($_POST['templateID']) || !is_numeric($_POST['templateID']) ){
            die( json_encode( array('code' => 400 , 'message' => '参数错误') ) );
        }

        try{

            $wms_print_template = new entity('wms_print_template');
            $wms_print_template->templateID = $_POST['templateID'];
            if(!$G_PGLOB->DBCA->fetch($wms_print_template)){
                die( json_encode( array('code' => 404 , 'message' => '模版信息未找到') ) );
            }
            $wms_print_template->isDefault = 1;
            $wms_print_template->useFlg = 1;

            //将所有默认置0
            $G_PGLOB->DBCA->stmt_query("UPDATE wms_print_template SET isDefault = 0 WHERE type = 1");

            $G_PGLOB->DBCA->save($wms_print_template);

            echo json_encode(array('code' =>200 ,'message' => 'ok'));

        }catch (Exception $e){
            error_log($e->getMessage());
            echo json_encode(array('code' => 500 ,'message' => '系统错误'));
        }

        return;
    }


}